<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          总记录条数：{{total}} 条
        </template>
        <el-button type="success"
                   size="small"
                   @click="$router.push('/import?type=employee')"
                   v-check="'POINT-USER-IMPORT'">导入</el-button>
        <el-button type="warning"
                   size="small"
                   @click="exportExcel"
                   v-check="'POINT-USER-EXPORT'">导出</el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   @click="showDialong = true"
                   v-check="'POINT-USER-ADD'">新增员工</el-button>
      </PageTools>
      <!-- 卡片 表格 -->
      <el-card>
        <el-table border
                  :data="list"
                  v-loading="loading">
          <el-table-column label="序号"
                           type="index"
                           width="100"
                           :index="indexFn"
                           align="center" />
          <el-table-column label="姓名"
                           prop="username"
                           align="center" />
          <el-table-column label="头像"
                           align="center">
            <template v-slot="{row}">
              <img v-imgerror="require('@/assets/common/img.jpeg')"
                   object-fit
                   style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                   :src="row.staffPhoto"
                   alt=""
                   @click="showCode(row.staffPhoto)">
            </template>

          </el-table-column>
          <el-table-column label="工号"
                           prop="workNumber"
                           align="center" />
          <el-table-column label="聘用形式"
                           align="center">
            <template v-slot="{row}">
              {{ hireType.find(item=> item.id === row.formOfEmployment).value }}
            </template>
          </el-table-column>
          <el-table-column label="部门"
                           prop="departmentName"
                           align="center" />
          <el-table-column label="入职时间"
                           align="center">
            <template v-slot="{row}">
              {{row.timeOfEntry | time}}
            </template>
          </el-table-column>
          <el-table-column label="账户状态"
                           prop="enableState"
                           align="center">
            <template v-slot="{row}">
              <!-- {{row.enableState === 1 ? '可用': '禁用'}} -->
              <el-switch :value="row.enableState === 1"
                         active-color="#13ce66"
                         inactive-color="#ff4949" />

            </template>
          </el-table-column>
          <el-table-column label="操作"
                           width="280"
                           align="center">
            <template v-slot="{row}">
              <el-button type="text"
                         size="small"
                         @click="$router.push(`/employees/detail/${row.id}`)"
                         v-check="'POINT-USER-UPDATE'">查看</el-button>
              <el-button type="text"
                         size="small">转正</el-button>
              <el-button type="text"
                         size="small">调岗</el-button>
              <el-button type="text"
                         size="small">离职</el-button>
              <el-button type="text"
                         size="small"
                         @click="assign(row.id)">角色</el-button>
              <el-button type="text"
                         size="small"
                         @click="del(row.id)"
                         v-check="'POINT-USER-DELETE'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex"
                justify="end"
                align="middle"
                style="height: 60px">
          <el-pagination layout="prev, pager, next, jumper"
                         background
                         :total="
                         total"
                         :page-size="size"
                         :current-page="page"
                         @current-change="changeFn" />
          <!-- @current-change 分页自带事件 -->
        </el-row>
      </el-card>
      <AddEmployee :showDialong.sync="showDialong"
                   @getEmployeeList="getEmployeeList"></AddEmployee>
      <!-- 二维码 -->
      <el-dialog title="二维码"
                 :visible.sync="showCodeDialog"
                 width="250px">
        <el-row type="flex"
                justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色 -->
      <AssignRole :showRoleDialog.sync="showRoleDialog"
                  :userId="userId"></AssignRole>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employess'
import EmployeeEnum from '@/api/constant/employees' // 引入枚举文件
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/AssignRole.vue'
// import { export_json_to_excel } from '@/utils/Export2Excel'  // 同步导出
import moment from 'moment'
import QrCode from 'qrcode' // 图片生成二维码 安装生成二维码的插件
import store from '@/store'

export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [], // 存放数据
      page: 1,  // 当前页
      size: 5, // 每页条数
      total: 0,    // 总条数
      loading: false,
      hireType: EmployeeEnum.hireType,
      showDialong: false,
      showCodeDialog: false, // 二维码
      //  AssignRole组件控制显示分配角色的对话框
      showRoleDialog: false,
      // AssignRole组件 当前用户的id
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // // 权限控制按钮
    // check(point) {
    //   // 如果point 在权限中那么这个按钮就因该显示出来
    //   const points = this.$store.state.user.userInfo.roles.points
    //   return points.some(item => item.toLowerCase() === point.toLowerCase())
    // },
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page, this.size)
      this.list = rows
      this.total = total
      this.loading = false
      // console.log(this.list)
    },
    // 分页改变
    changeFn(value) {
      // console.log(value)
      this.page = value
      this.getEmployeeList() // 重新渲染
    },
    // 序号
    indexFn(index) {
      // 需要加上前面的页数 * 每页的条数
      return (index + 1) + (this.page - 1) * this.size
    },

    // 删除员工
    async del(id) {
      try {
        await this.$confirm('你确定要删除吗', '温馨提示', { type: 'warning' })
      } catch {
        return
      }
      await delEmployee(id)
      this.$message.success('删除成功')
      // 判断数组里 长度等于1时 当前页减1
      if (this.list.length === 1) {
        this.page--
      }
      this.getEmployeeList()
    },
    // 导出方法
    async exportExcel() {
      const excel = await import('@/utils/Export2Excel')
      // 发送ajax请求，获取所有员工的数据
      const { rows } = await getEmployeeList(1, 1000)
      const userRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime'
      }
      const header = Object.keys(userRelations)
      // [''入职日期', '手机号', '姓名']
      const data = []
      rows.forEach(item => {
        const arr = []
        header.forEach(h => {
          // 额外判断
          if (h === '入职日期' || h === '转正日期') {
            // 只想要年月日
            let time = item[userRelations[h]]
            if (time) {
              time = moment(item[userRelations[h]]).format('YYYY-MM-DD')
            }
            arr.push(time)
          } else if (h === '聘用形式') {
            // console.log(item[userRelations[h]])
            const result = EmployeeEnum.hireType.find(v => v.id === +item[userRelations[h]])
            arr.push(result ? result.value : '其他')
          } else {
            arr.push(item[userRelations[h]])
          }
        })
        data.push(arr)
      })
      excel.export_json_to_excel({
        header,
        data,
        filename: '员工数据',
        bookType: 'xlsx'
      })
    },
    // 点击图片 生产二维码
    async showCode(photo) {
      console.log(photo)
      this.showCodeDialog = true
      await this.$nextTick()
      // dom：把二维码生成到哪个DOM上
      // info: 生成二维码的信息  可以是一个url地址  文本 图片
      // QrCode.toCanvas(dom, info)
      QrCode.toCanvas(this.$refs.myCanvas, photo)
    },
    // 角色
    assign(id) {
      this.userId = id
      this.showRoleDialog = true
    }
  }
}




</script>

<style>
</style>
